/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.emobile.biz.api.controller.ApiProfileController.java 
 * <p>
 * 类产生时间: 2014/4/19 23:12
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package cn.com.oceansoft.business.sys.controller;

import cn.com.oceansoft.business.base.controller.BaseController;
import cn.com.oceansoft.business.base.entity.Result;
import cn.com.oceansoft.business.log.persistence.ISysOperLogMapper;
import cn.com.oceansoft.business.log.service.IOperLogService;
import cn.com.oceansoft.business.sys.entity.SysUser;
import cn.com.oceansoft.business.sys.service.ISysResourceService;
import cn.com.oceansoft.business.sys.service.ISysUserService;
import cn.com.oceansoft.business.szjf.entity.Sms;
import cn.com.oceansoft.business.szjf.service.ISmsService;
import cn.com.oceansoft.nos.common.ISMSService;
import cn.com.oceansoft.nos.common.util.SessionUtil;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Set;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 用户账号管理控制器
 *
 * @author: chenw
 * @time: 2014/4/19 23:12
 */
@Controller
@RequestMapping("profile")
public class ProfileController extends BaseController {

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private ISysResourceService resourceService;

    @Resource
    private ISmsService smsRecordsService;

    @Resource
    private IOperLogService sysOperLogService;



    @RequestMapping("login")
    public String gotoLogin(HttpServletRequest request,Model model) {

        try {
            String guid = "";

            if(null != getSession()){
                return gotoIndex(request,model);
            }


            if(StringUtils.hasText(guid)){
                //获取用户信息
                SysUser sysUser = sysUserService.findUserById(guid);
                sysUser.setPassword("");
                //加载用户权限资源
                Set<String> resources = resourceService.findResourceByUserId(guid);
                saveSession(sysUser);
//                savePrivilege(resources);
                log(String.format("用户%s登录成功", sysUser.getPhone()));
                 //跳转至首页
                return gotoIndex(request,model);
            }
        }catch (RuntimeException e){
            return "admin/profile-login";
        }

        return "admin/profile-login";
    }

    @RequestMapping("re-login")
    public String gotoReLogin() {
        return "admin/ajax-login";
    }

    @RequestMapping("index")
    public String gotoIndex(HttpServletRequest request,Model model) {
        //加载当前用户菜单
        /*String flag = request.getParameter("flag");
        if(StringUtils.hasText(flag)){
            model.addAttribute("flag",flag);
        }*/
        return "szjf/shlx";
    }

    @RequestMapping(value = "setting", method = GET)
    public String gotoSetting() {
        return "admin/profile-setting";
    }

    @ResponseBody
    @RequestMapping(value = "setting", method = POST)
    public Result updatePassword(SysUser user) {
        SysUser sess = getSession();
        sess.setPassword(user.getPassword());
//        sess.setOldPwd(user.getOldPwd());
//        log(String.format("用户%s修改个人信息", sess.getLoginId()));
        return sysUserService.updateUserAccountInfo(sess);
    }


    @ResponseBody
    @RequestMapping(value = "auth", method = POST)
    public Result loginAuth(SysUser sysUser) {
        if (StringUtils.hasText(sysUser.getPhone()) && StringUtils.hasText(sysUser.getTemp3())) {
            //验证登陆信息
            Result rt = sysUserService.checkLogin(sysUser);
            //验证成功
            if (rt.isSucc()) {
                //加载用户权限资源
//                Set<String> resources = resourceService.findResourceByUserId(((SysUser) rt.getData()).getId());
//                savePrivilege(resources);
//                SysUser = sysUserService.getUserPosition((SysUser)rt.getData());
                //user放入session
                saveSession(((SysUser) rt.getData()));

                log(String.format("用户%s登录成功", sysUser.getRealname()));
                sysOperLogService.insertLog("管理员登录","AdminLogin","登录日志","管理用户【"+((SysUser) rt.getData()).getUsername()+"】登录",((SysUser) rt.getData()).getGuid());

            } else {
                log(String.format("用户%s尝试登录系统失败，验证码过期或者错误", sysUser.getPhone()));
            }
            return rt;
        } else {
            log(String.format("用户%s尝试登录系统失败，验证码过期或者错误", sysUser.getPhone()));
            return new Result(Result.FAILURE, "验证码过期或者错误");
        }
//        return new Result(Result.SUCC,"成功");
    }

    @RequestMapping(value = "logout", method = GET)
    public String logout(HttpSession session) {
        log(String.format("用户%s退出系统", getSession()));
        SessionUtil.invalidate(session);
        return "redirect:login";
    }

    /**
     * 获取验证码，并发送短信，后入库
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getvericode")
    public Result GetVeriCode(String phone){
        Result result=new Result();
        SysUser user = sysUserService.findUserByPhone(phone);

        //用户不存在
        //用户不是管理员
        if(user==null){
            result.setMsg("当前账号不存在");
            result.setStatusCode(1);
        }else if (!"1".equals(user.getUserlevel())) {
            result.setMsg("当前账号不能进行登录");
            result.setStatusCode(2);
        } else {
            int suc = 2;
            int code = GetMesgCode();//生成验证码
            String smsContent = "您的验证码为:" + code + "，此验证码在120秒过期。";
            try {
                suc = smsRecordsService.sendMsm(user.getPhone(), smsContent);
            } catch (Exception e) {
                e.printStackTrace();

                result.setMsg("发送短信失败");
                result.setStatusCode(3);
            }
            try{
                //发送成功，存入USERSMSCODE表
                if (suc == 1) {
                    Sms userSms = new Sms();
                    Calendar c= Calendar.getInstance();
                    userSms.setCreatetime(c.getTime());
                    userSms.setSmscode(code);
                    c.add(Calendar.MINUTE,2);//过期时间是2分钟
                    userSms.setOverduetime(c.getTime());
                    userSms.setPhone(phone);
                    smsRecordsService.insertUserSms(userSms);
                }
                //存入SMSRecords表
                Sms sms = new Sms();
                sms.setSmsno(smsRecordsService.getNewSmsNo());
                sms.setReceivephone(phone);
                sms.setRecipient(user.getRealname());
                sms.setSender("管理员");
                sms.setSendtime(new Date());
                sms.setSmstype("0");//1通知类，0回访类
                sms.setSmstitle("");
                sms.setSmscontent(smsContent);
                sms.setSmsstate(suc);//0发送失败，1发送成功， 2未发送
                sms.setIstiming("0");
                smsRecordsService.insertSMSRecords(sms);

                result.setMsg("发送短信成功");
                result.setStatusCode(4);
            }catch (Exception e){
                e.printStackTrace();
                result.setMsg("短信信息入库失败");
                result.setStatusCode(5);
            }

        }
        return result;
    }


    /**
     * 生成验证码
     * @return
     */
    private static int GetMesgCode()
    {
        int length = 6; //int.Parse(AppSettingHelper.GetConfigKey("PhoneCodeLength"));//激活码长度
        int min = 9;
        for (int i = 0; i < length - 2; i++)
        {
            min = min * 10 + 9;
        }
        Random r = new Random();
        int code = r.nextInt(min * 10 + 9);
        return code;
    }

    public static void main(String[] args) {
        int a = GetMesgCode();
        int b = GetMesgCode();
        int c = GetMesgCode();
        int d = GetMesgCode();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");
        Calendar cc= Calendar.getInstance();
        System.out.println(sdf.format(cc.getTime()));
        cc.add(Calendar.MINUTE,2);
        System.out.print(sdf.format(cc.getTime()));

    }
}

